<template>
  <div class="info-box">
    <div>
      <a-button @click="emit('returnPage')">返回</a-button>
      <span class="text-base font-bold pl-5">客户详情查看</span>
    </div>
    <a-divider />
    <a-card :bordered="false">
      <div class="title-name">{{ baseInfo?.name }}</div>
      <div class="title-info">
        <span>客户类型：{{ baseInfo?.typeName }}</span>
        <span>所在行业：{{ baseInfo?.industry }}</span>
        <span>来源：{{ baseInfo?.sourceName }}</span>
        <span>规模：{{ baseInfo?.scaleName }}</span>
        <span>公司性质：{{ baseInfo?.natureName }}</span>
        <span>地址：{{ baseInfo?.address }}</span>
        <span v-if="!isCommon">归属：{{ baseInfo?.saleName }}</span>
      </div>
    </a-card>
    <a-tabs v-model:activeKey="activeKey">
      <a-tab-pane key="1" tab="跟进记录" v-if="!isCommon">
        <BasicTable @register="registerFollowTable">
          <template #toolbar>
            <a-button type="primary" @click="handleFollowCreate">新增跟进</a-button>
          </template>
          <template #bodyCell="{ column, record }">
            <template v-if="column.dataIndex == 'action'">
              <TableAction
                :actions="[
                  {
                    icon: 'clarity:note-edit-line',
                    onClick: handleFollowEdit.bind(null, record),
                  },
                  {
                    icon: 'ant-design:delete-outlined',
                    color: 'error',
                    onClick: handleFollowDelete.bind(null, record),
                  },
                ]"
              />
            </template>
          </template>
        </BasicTable>
      </a-tab-pane>
      <a-tab-pane key="2" tab="客户信息">
        <div class="sub-title">客户信息</div>
        <a-card :bordered="false">
          <div class="title-info flex">
            图片资料：
            <a-image-preview-group v-if="imgList.length">
              <a-image v-for="(item, index) in imgList" :key="index" :src="item.fileUrl" />
            </a-image-preview-group>
            <span v-else>暂无图片</span>
          </div>
        </a-card>
        <div class="sub-title other-info">其他信息</div>
        <a-card :bordered="false">
          <div class="title-info">
            <span>创建日期：{{ baseInfo?.createDate }}</span>
            <span>创建人：{{ baseInfo?.createUserName }}</span>
          </div>
        </a-card>
      </a-tab-pane>
      <a-tab-pane key="3" tab="联系人">
        <BasicTable @register="registerContactsTable">
          <template #toolbar>
            <a-button type="primary" @click="handleContactsCreate">新增联系人</a-button>
          </template>
          <template #bodyCell="{ column, record }">
            <template v-if="column.dataIndex == 'action'">
              <TableAction
                :actions="[
                  {
                    icon: 'clarity:note-edit-line',
                    onClick: handleContactsEdit.bind(null, record),
                  },
                  {
                    icon: 'ant-design:delete-outlined',
                    color: 'error',
                    onClick: handleContactsDelete.bind(null, record),
                  },
                ]"
              />
            </template>
          </template>
        </BasicTable>
      </a-tab-pane>
      <a-tab-pane key="4" tab="操作记录">
        <BasicTable @register="registerLogTable" />
      </a-tab-pane>
    </a-tabs>
  </div>
  <FollowModal @register="registerFollowModal" @success="reload('follow')" />
  <ContactsModal @register="registerContactsModal" @success="reload('contact')" />
</template>
<script lang="ts" setup>
  import { onMounted, ref, createVNode, watch } from 'vue';
  import { BasicTable, TableAction, useTable, BasicColumn, FormSchema } from '/@/components/Table';
  import { getDetailInfo, deleteFollowCustomer, deleteContacts } from '/@/api/erp/customer/list';
  import { getFileList } from '/@/api/system/file';
  import { useModal } from '/@/components/Modal';
  import FollowModal from './FollowModal.vue';
  import ContactsModal from './ContactsModal.vue';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { Modal } from 'ant-design-vue';
  import { ExclamationCircleOutlined } from '@ant-design/icons-vue';
  import { isNil } from 'lodash-es';

  const contactsColumns: BasicColumn[] = [
    {
      dataIndex: 'name',
      title: '联系人',
      align: 'center',
    },

    {
      dataIndex: 'phone',
      title: '电话',
      align: 'center',
    },
    {
      dataIndex: 'post',
      title: '职位',
      align: 'center',
    },
    {
      dataIndex: 'dept',
      title: '部门',
      align: 'center',
    },
    {
      dataIndex: 'createDate',
      title: '创建时间',
      align: 'center',
    },
    {
      dataIndex: 'createUserName',
      title: '创建人',
      align: 'center',
    },
    {
      dataIndex: 'isDefault',
      title: '是否默认',
      align: 'center',
      customRender: ({ text }) => {
        return text ? '是' : '否';
      },
    },
  ];
  const followColumns: BasicColumn[] = [
    {
      dataIndex: 'followTime',
      title: '跟进时间',
      align: 'center',
    },
    {
      dataIndex: 'nextFollowTime',
      title: '下次跟进时间',
      align: 'center',
    },
    {
      dataIndex: 'followTypeName',
      title: '跟进方式',
      align: 'center',
    },
    {
      dataIndex: 'content',
      title: '说明',
      align: 'center',
    },
    {
      dataIndex: 'createUserName',
      title: '跟进人',
      align: 'center',
    },
  ];
  const logColumns: BasicColumn[] = [
    {
      dataIndex: 'operateUserAccount',
      title: '操作人',
      align: 'center',
    },
    {
      dataIndex: 'createDate',
      title: '操作时间',
      align: 'center',
    },
    {
      dataIndex: 'executeResultJson',
      title: '操作内容',
      align: 'center',
    },
  ];

  const searchFormSchema: FormSchema[] = [
    {
      field: 'keyword',
      label: '',
      component: 'Input',
      colProps: { span: 4 },
      componentProps: {
        placeholder: '请输入要查询的关键字',
      },
    },
  ];

  const { t } = useI18n();

  const props = defineProps({
    id: String,
    isCommon: {
      type: Boolean,
      default: false,
    },
  });
  const emit = defineEmits(['returnPage']);
  const followInfoDataSource = ref<any>([]);
  const contactsInfoDataSource = ref<any>([]);
  const logInfoDataSource = ref<any>([]);
  const activeKey = ref('1');
  const baseInfo = ref();
  const imgList = ref<any>([]);
  const { notification } = useMessage();

  const [registerFollowModal, { openModal: openFollowModal }] = useModal();
  const [registerContactsModal, { openModal: openContactsModal }] = useModal();

  watch(
    () => props.isCommon,
    (val) => {
      activeKey.value = val ? '2' : '1';
    },
    {
      immediate: true,
    },
  );

  const [registerFollowTable, { reload: reloadFollow }] = useTable({
    dataSource: followInfoDataSource,
    rowKey: 'id',
    columns: followColumns,
    bordered: true,
    pagination: false,
    actionColumn: {
      width: 120,
      title: t('操作'),
      dataIndex: 'action',
      slots: { customRender: 'action' },
    },
  });
  const [registerContactsTable, { reload: reloadContact }] = useTable({
    dataSource: contactsInfoDataSource,
    rowKey: 'id',
    columns: contactsColumns,
    bordered: true,
    pagination: false,
    actionColumn: {
      width: 120,
      title: t('操作'),
      dataIndex: 'action',
      slots: { customRender: 'action' },
    },
  });
  const [registerLogTable, { setProps }] = useTable({
    dataSource: logInfoDataSource,
    rowKey: 'id',
    columns: logColumns,
    handleSearchInfoFn(info) {
      const filterData = logInfoDataSource.value.filter((item) => {
        for (const key in item) {
          if (!isNil(item[key]) && item[key].toString().indexOf(info.keyword) > -1) {
            return item;
          }
        }
      });
      setProps({ dataSource: filterData });
      return info;
    },
    formConfig: {
      schemas: searchFormSchema,
    },
    useSearchForm: true,
    bordered: true,
    pagination: false,
  });

  onMounted(() => {
    getInfo();
  });

  const getInfo = async () => {
    const res = await getDetailInfo(props.id!);
    baseInfo.value = res?.caseErpCustomerVo;
    followInfoDataSource.value = res?.caseErpCustomerFollowInfoVoList;
    contactsInfoDataSource.value = res?.caseErpCustomerContactsInfoVoList;
    logInfoDataSource.value = res?.caseErpLogList.map((x) => {
      return {
        operateUserAccount: x.operateUserAccount,
        createDate: x.createDate,
        executeResultJson: x.executeResultJson,
      };
    });
    if (baseInfo.value.filePath) {
      imgList.value = await getFileList({ folderId: baseInfo.value.filePath });
    }
  };

  const reload = (type) => {
    getInfo();
    type === 'follow' ? reloadFollow() : reloadContact();
  };

  const handleFollowCreate = () => {
    openFollowModal(true, {
      record: baseInfo.value,
    });
  };

  const handleFollowEdit = (record) => {
    openFollowModal(true, {
      record: baseInfo.value,
      id: record.id,
      isUpdate: true,
    });
  };

  const handleFollowDelete = (record) => {
    Modal.confirm({
      title: t('提示信息'),
      icon: createVNode(ExclamationCircleOutlined),
      content: t('是否确认删除？'),
      okText: t('确认'),
      cancelText: t('取消'),
      async onOk() {
        await deleteFollowCustomer(record.id);
        notification.success({
          message: t('提示'),
          description: t('删除成功'),
        });
        reload('follow');
      },
      onCancel() {},
    });
  };

  const handleContactsCreate = () => {
    openContactsModal(true, {
      customerId: props.id,
      isUpdate: false,
    });
  };

  const handleContactsEdit = (record) => {
    openContactsModal(true, {
      customerId: props.id,
      id: record.id,
      isUpdate: true,
    });
  };

  const handleContactsDelete = (record) => {
    Modal.confirm({
      title: t('提示信息'),
      icon: createVNode(ExclamationCircleOutlined),
      content: t('是否确认删除？'),
      okText: t('确认'),
      cancelText: t('取消'),
      async onOk() {
        await deleteContacts(record.id);
        notification.success({
          message: t('提示'),
          description: t('删除成功'),
        });
        reload('contact');
      },
      onCancel() {},
    });
  };
</script>
<style lang="less" scoped>
  .info-box {
    background-color: #fff;
    width: 100%;
    height: 100%;
    padding: 16px;
    margin-right: 8px;

    .title-name {
      font-size: 18px;
      color: #444;
      font-weight: 700;
      margin-bottom: 25px;
    }

    .title-info span {
      margin-right: 40px;
    }

    .sub-title {
      font-weight: 700;
      margin-bottom: 24px;
    }

    .other-info {
      margin-top: 24px;
    }
  }

  :deep(.ant-image) {
    width: 100px;
    height: 75px;
    padding: 5px;
    border: 1px solid silver;
    border-radius: 4px;
    margin-right: 10px;
  }

  :deep(.ant-image-img) {
    height: 100%;
  }

  :deep(.ant-divider) {
    height: 1px;
    background-color: #dcdfe6;
  }

  :deep(.ant-card-body) {
    background-color: #f8f8f8;
  }

  :deep(.ant-tabs) {
    height: 70%;
  }

  :deep(.ant-tabs-content) {
    height: 100%;
  }
</style>
